import { Body, Controller, Get, Headers, Ip, Logger, Post, Req, Session } from "@nestjs/common";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
import session from "express-session";

import { SkipJwtAuth } from "@/core/auth/decorator/skip-auth.decorator";
import { ApiBaseResponse } from "@/core/decorators/api-base-response.decorator";
import AjaxResult from "@/core/utils/AjaxResult";

import { SysUserLoginDto } from "./dto/login.dto";
import { RegisterDto } from "./dto/register.dto";
import { LoginService } from "./login.service";
import { LoginVo } from "./vo/login.vo";

@ApiTags("管理员登录")
@Controller("/admin/login")
export class AdminLoginController {
    private readonly logger = new Logger(AdminLoginController.name);
    constructor(private readonly loginService: LoginService) {}

    @ApiOperation({ summary: "验证码" })
    @SkipJwtAuth()
    @Get("/captcha")
    async getCaptcha(@Session() session: session.Session & Partial<session.SessionData>) {
        if (!session) return AjaxResult.fail();
        console.log("session.id---", session?.id);
        const captcha = await this.loginService.getCaptcha(session);
        console.log("session", session?.captcha);
        // session.destroy((err: Error) => {
        //     if (err) throw "session destroy error";
        // });
        return AjaxResult.success(captcha);
    }

    @ApiOperation({ summary: "账号登录" })
    @SkipJwtAuth()
    @ApiBaseResponse(LoginVo)
    @Post("/account")
    async loginByAccount(
        @Body() loginDto: SysUserLoginDto,
        @Ip() ip: string,
        @Headers("User-Agent") userAgent: string,
        @Session() session: session.Session & Partial<session.SessionData>
    ) {
        this.logger.debug(ip);
        this.logger.debug(userAgent);
        this.logger.debug(session?.id);
        this.logger.debug(loginDto);

        if (loginDto.terminal === "pc") {
            return AjaxResult.success(
                await this.loginService.login(
                    loginDto.username,
                    loginDto.password,
                    ip,
                    userAgent,
                    loginDto.captcha,
                    session
                )
            );
        } else {
            // TODO 移动端登录
            return AjaxResult.fail(400, "登录终端错误");
        }
    }

    @ApiOperation({ summary: "登出" })
    @ApiBearerAuth()
    @Get("/logout")
    async logout(@Req() req, @Session() session: session.Session & Partial<session.SessionData>) {
        await this.loginService.logout(req.user.id);
        session?.destroy((err: Error) => {
            if (err) new Error("session destroy error");
        });
        return AjaxResult.success();
    }

    // 其实管理系统不存在注册功能，新用户都是通过管理员手动添加的，这里只提供登录注册接口
    @ApiOperation({ summary: "账号注册" })
    @SkipJwtAuth()
    @Post("/account/register")
    async register(@Body() registerDto: RegisterDto) {
        await this.loginService.register(registerDto.username, registerDto.password, registerDto.email);
        return AjaxResult.success();
    }
}
